package com.example.pest.util;

import cn.hutool.json.JSONUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.pest.bean.RoleEnum;
import com.example.pest.bean.TokenBean;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

/**
 * JWT工具类
 */
@Slf4j
public class JwtUtil {
    // Token过期时间1天
    private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;
    // 密钥
    private static final String SECRET = "jd980018267773dd@@";
    // 算法
    private static final Algorithm ALGORITHM = Algorithm.HMAC256(SECRET);
    // JWT验证器
    private static final JWTVerifier VERIFIER = JWT.require(ALGORITHM).build();

    /**
     * 生成Token
     */
    public static String createToken(TokenBean tokenBean) {
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            return JWT.create()
                    .withClaim("info", JSONUtil.toJsonStr(tokenBean))
                    .withExpiresAt(date)
                    .sign(ALGORITHM);
        } catch (Exception e) {
            log.error("生成Token异常", e);
            throw new RuntimeException("Token创建异常");
        }
    }

    /**
     * 验证Token
     */
    public static void verifyToken(String token) {
        try {
            VERIFIER.verify(token);
        } catch (Exception e) {
            log.error("Token验证异常", e);
            throw new RuntimeException("token过时");
        }
    }

    /**
     * 获取Token中的用户ID
     */
    public static TokenBean getTokenBean(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return JSONUtil.toBean(jwt.getClaim("info").asString(), TokenBean.class);
        } catch (JWTDecodeException e) {
            log.error("获取用户ID异常", e);
            throw new RuntimeException("token过时");
        }
    }

    public static TokenBean getTokenBean() {
        ServletRequestAttributes servletRequestAttributes =  (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String token = request.getHeader("JWT");
        if (null == token) {
            return null;
        }
        DecodedJWT jwt = JWT.decode(token);
        return JSONUtil.toBean( jwt.getClaim("info").asString(), TokenBean.class);
    }

    public static boolean isManage(){
        return getTokenBean().getRole().equals(RoleEnum.manage.name());
    }

    public static boolean isConsume(){
        return getTokenBean().getRole().equals(RoleEnum.consume.name());
    }
} 